<!-- 采购管理-采购任务列表 -->
<template>
  <pageHeader title="新建采购计划" :breadCrumb="breadCrumb" :show-back="true">
    <template #footer>
      <a-button @click="router.back()">
        <template #default>取消</template>
      </a-button>
      <!-- <a-button type="primary" @click="save">
        <template #default>保存</template>
      </a-button> -->
      <a-button type="primary" @click="handleOk">
        <template #default>提交</template>
      </a-button>
    </template>
    <div class="title">
      <h1>采购计划表</h1>
    </div>
    <div>
      <div class="title-item">
        <a-space style="margin-left: 40px">
          <div
            style="
              width: 5px;
              height: 23px;
              background-color: rgba(61, 126, 255, 1);
              border: none;
              border-radius: 2px;
            "
          ></div>
          <div>基本信息</div></a-space
        >
      </div>
      <div class="demand-index">
        <a-form
          ref="refForm"
          :model="demand.info"
          autoLabelWidth
          :layout="(layout as Tlayout)"
        >
          <a-row :gutter="16">
            <a-col
              v-for="item in demandForm?.info?.design?.form"
              :key="item.id"
              :span="item.span"
            >
              <FormItem
                :name="item.name"
                :componentType="item.componentType"
                v-model:props="item.props"
                :required="item.required"
                :disabled="item.disabled"
                v-model:values="item.values"
              />
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
  </pageHeader>

  <!-- <div style="margin-left: 60px">
    <a-space>
      <div>是否自动生成订单：</div
      ><div
        ><a-switch
          v-model="demand.info.isAutoToOrder"
          :checked-value="1"
          :unchecked-value="2"
      /></div>
    </a-space>
  </div> -->
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import dayjs from 'dayjs';
  import { putPlanPurchase } from '@/api/buy-management/buy-plan/index';
  // import { postPurchaseApply } from '@/api/buy-management/buy-apply/index';
  import {
    getPurchasePlanDetail,
    putPlanPurchaseList,
  } from '@/api/buy-management/buy-plan/index';
  import { getOpenTemp } from '@/api/buy-management/get-template/index';
  import miiter from '@/utils/mitt';
  import { Message } from '@arco-design/web-vue';

  const router = useRouter();
  const route = useRoute();
  const refForm = ref();
  const breadCrumb: string[] = ['采购管理', '采购管理', '新建采购计划'];
  const userInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  const layout = ref('vertical');
  type Tlayout = 'inline' | 'horizontal' | 'vertical' | undefined;
  interface DemandType {
    info: {
      number: string;
      createBy: number;
      deptId: number;
      name: string;
      state: number;
      description: string;
      templateId: number;
      fileIds: any;
      extend: string;
      purchasePlan: any;
      isAutoToOrder: number;
      file: any;
      addIds: any;
      deleteIds: any;
      product: any;
    };
  }
  const demand = reactive<DemandType>({
    info: {
      number: '',
      name: '',
      state: 0,
      description: '',
      deptId: 0,
      createBy: 0,
      fileIds: '',
      templateId: 0,
      extend: '',
      purchasePlan: [],
      product: [],
      isAutoToOrder: 2,
      file: [],
      addIds: [],
      deleteIds: [],
    },
  });
  interface DemandFormType {
    info: {
      id: number;
      flowId: number;
      design: {
        form: any[];
      };
    };
  }
  const demandForm = reactive<DemandFormType>({
    info: { id: 0, flowId: 0, design: { form: [] } },
  });
  const isAutoToOrder = ref();

  const getTemp = async () => {
    const res = await getOpenTemp({ type: 2 });
    demandForm.info = res;
    demandForm.info.design.form.sort((a: any, b: any) => a.sort - b.sort);
    demandForm.info.design.form.forEach((item: any) => {
      item.props = JSON.parse(item.props);
      if (item.values !== '') {
        item.values = JSON.parse(item.values);
        if (item.values[0] === '') {
          item.values = [];
        }
      }
      if (item.code === 'BUY-PLAN-DETAILS') {
        item.props.data = demand.info.product || [];
        item.props.deleteIds = [];
        item.props.addIds = [];
        item.props.number = demand.info.number;
      }
      if (item.code === 'TEXT') {
        item.disabled = true;
        item.values = [demand.info.name];
      }
      if (item.code === 'NUMBER-UNIVERSAL') {
        item.disabled = true;
        item.values = [demand.info.number];
      }
      if (item.code === 'CREATED_DY') {
        item.values = [userInfo.id];
      }
      if (item.code === 'APPLY_DEPT') {
        item.values = [userInfo.department.id];
      }
      if (item.code === 'APPLY_DATE') {
        item.values = [demand.info.createdAt];
      }
    });
  };

  const getPlanDetail = async () => {
    const res = await getPurchasePlanDetail({ id: route.query.id });
    demand.info = res.planData;
    demand.info.isAutoToOrder = 1;
    getTemp();
  };

  getPlanDetail();

  const visible = ref(false);
  const keys = Object.keys(demand.info);

  const handleClick = () => {
    visible.value = true;
  };

  const handleOk = async () => {
    if (await refForm.value.validate()) return;
    demandForm.info.design.form.forEach((item) => {
      if (item.fieldName && keys.includes(item.fieldName)) {
        demand.info[item.fieldName] = item.values[0];
      }
      if (item.code === 'FILE') {
        demand.info.file = item.props.data;
        demand.info.file[0].moduleType = 2;
        delete demand.info.file[0].id;
      }
      if (item.code === 'BUY-PLAN-DETAILS') {
        demand.info.product = item.props.data;
        demand.info.addIds = item.props.addIds;
        demand.info.deleteIds = item.props.deleteIds;
      }
    });
    demand.info.state = 3;
    demand.info.templateId = demandForm.info.id;
    demand.info.extend = JSON.stringify(demandForm.info.design.form);
    demand.info.purchasePlan = {
      ...demand.info,
    };
    delete demand.info.purchasePlan.addIds;
    delete demand.info.purchasePlan.deleteIds;
    demand.info.product.forEach((item) => {
      if (item.planAmount < item.amount) {
        Message.warning(
          `${item.name}的计划采购数量小于实际需求数量，将被视为异常完成。`
        );
      }
    });
    await putPlanPurchaseList({
      purchasePlan: demand.info.purchasePlan,
      addIds: demand.info.addIds,
      deleteIds: demand.info.deleteIds,
    });
    router.back();
    // }
  };

  miiter.on('key', (val) => {
    if (val) {
      getPlanDetail();
    }
  });
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .title {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
  }
  .demand-index {
    padding: 25px 140px;
  }
</style>
